<template>
  <div class="app-container">
    <el-scrollbar class="form-scrollbar">
      <el-card class="box-card" shadow="never">
        <div>
          <el-row>
            <el-col :span="6" style="text-align: right">
              <el-select
                v-model="tableName"
                @change="selectChange"
                placeholder="请选择要导入的表"
              >
                <el-option
                  v-for="item in tables"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2"><div></div></el-col>
            <el-col :span="6">
              <el-upload
                class="upload-demo"
                action=""
                :on-change="handleChange"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :file-list="fileListUpload"
                :limit="limitUpload"
                accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                :auto-upload="false"
              >
                <el-button size="small" :disabled="btnFlag" type="primary"
                  >选择文件</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  只 能 上 传 csv/xlsx/xls 文 件
                </div>
                <div>加载进度：{{ msg }}</div>
              </el-upload>
            </el-col>
            <el-col :span="10"></el-col>
          </el-row>
          <el-row v-show="ShowDiv">
            <el-col>
              <div v-if="totalCount > 0">
                <el-table
                  style="width: 100%"
                  :data="
                    tableData.slice(
                      (currentPage - 1) * pagesize,
                      currentPage * pagesize
                    )
                  "
                >
                  <el-table-column
                    v-for="col in cols"
                    :prop="col.prop"
                    :label="col.label"
                  >
                  </el-table-column>
                </el-table>
                <div style="pagebox">
                  <el-pagination
                    class="explore_right_pages"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 40]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount"
                  >
                  </el-pagination>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row v-show="ShowDiv">
            <el-col>
              <el-checkbox v-model="checked">确认导入上表的数据吗</el-checkbox>
            </el-col>
          </el-row>
          <el-row v-show="checked">
            <el-col>
              <el-button
                size="small"
                type="primary"
                :disabled="btnFlag"
                @click="uploadExcel"
                >开始上传
              </el-button>
            </el-col>
          </el-row>
          <el-row v-show="checked">
            <el-col>
              <div style="height: 300px; overflow-y: auto">
                <el-progress
                  :text-inside="true"
                  :stroke-width="24"
                  :percentage="percentage"
                  status="success"
                ></el-progress>
                <el-card class="box-card">
                  <div
                    style="
                      font-size: 13px;
                      color: #1f2d3d;
                      margin-top: 7px;
                      width: 50%;
                      height: 200px;
                      overflow-y: auto;
                    "
                  >
                    <el-row>
                      <el-col :span="6">总数据量：{{ totalCount }}</el-col>
                      <el-col :span="6">已执行：{{ processCount }}</el-col>
                      <el-col :span="6">失败：{{ errorCount }}</el-col>
                      <el-col :span="6">总计时长：{{ totalTime }}ms</el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="4"><div>执行日志：</div></el-col>
                      <el-col :span="20"
                        ><div v-html="processMsg"></div
                      ></el-col>
                    </el-row>
                  </div>
                </el-card>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-scrollbar>
  </div>
</template>
<script src="./is-utf8.js"/>
<script src="./codepage.js"/>
<script>
import { isUTF8 } from "@/views/customsData/is-utf8.js";
import XLSX from "xlsx";
import { postAction } from "@/api/common";
/* import { Loading } from "element-ui"; */

export default {
  data() {
    return {
      btnFlag: false,
      ShowDiv: false,
      checked: false,
      //file
      limitUpload: 1, //上传文件数量显示
      fileListUpload: [],
      fileTemp: null, //存放组件上传的excel file 用于实现读取数据
      //table
      tableData: null,
      cols: [],
      pagesize: 10,
      currentPage: 1,
      totalCount: 0, //总数量
      //process
      percentage: 0,
      processCount: 0, //成功执行的数量
      errorCount: 0,
      processMsg: "", //执行日志
      totalTime: 0,
      msg: "",
      //select
      tables: [
        {
          value: "TradeMode",
          label: "贸易方式",
        },
        {
          value: "Commodity",
          label: "商品表",
        },
        {
          value: "TradePartner",
          label: "贸易伙伴",
        },
        {
          value: "Province",
          label: "国内省市",
        },
        {
          value: "ExportCommodity",
          label: "主要出口商品参数",
        },
        {
          value: "ImportCommodity",
          label: "主要进口商品参数",
        },
        {
          value: "UOMAdjustment",
          label: "计量单位调整",
        },
        {
          value: "TradeData",
          label: "贸易数据表",
        },
      ],
      tableName: "",
    };
  },
  watch: {
    fileTemp(val) {
      if (val) {
        console.log(val.type);
        if (
          val.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          val.type == "application/vnd.ms-excel"
        ) {
          this.importExcelData(val);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      }
    },
  },
  methods: {
    sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    },
    async uploadExcel() {
      let _this = this;
      //先需要初始化数据
      _this.percentage = 0;
      _this.processCount = 0; //成功执行的数量
      _this.errorCount = 0;
      //冻结按钮操作
      _this.btnFlag = true;

      var dt = _this.tableData;
      var itemCount = 1000; //每次导入的数量
      var retryTimes = 0; //出错重试的次数
      var SumCount = Math.floor(dt.length / itemCount);
      var ModCount = dt.length % itemCount;
      var count = ModCount > 0 ? SumCount + 1 : SumCount;
      for (var i = 1; i <= count; i++) {
        debugger;
        var start = performance.now(); //记录时间
        var dataSource = dt.slice((i - 1) * itemCount, i * itemCount);
        debugger;
        let actionName = "CustomsData/uploadExcel" + _this.tableName;
        let result = await postAction(dataSource, actionName);
        if (result.code == "20000") {
          retryTimes = 0;
          _this.processCount += result.data;
          _this.percentage = Math.floor(
            (_this.processCount / _this.totalCount) * 100
          );
          var end = performance.now();
          var time = Math.floor(end - start);
          _this.totalTime += time;
          _this.processMsg +=
            "<br/>本次成功执行" + result.data + "条，花费时间：" + time + "ms";
        } else {
          if (retryTimes > 2) {
            //取消重试，直接记录下来即可
            debugger;
            retryTimes = 0;
            _this.errorCount += 1;
            _this.processMsg +=
              "<br/>id:" +
              i +
              "，执行失败，id：" +
              i +
              ",错误信息:" +
              result.message;
          } else {
            retryTimes += 1;
            _this.processMsg +=
              "<br/>id:" +
              i +
              "，执行失败，等待" +
              Math.pow(2, retryTimes) +
              "秒后重试";
            await _this.sleep(Math.pow(2, retryTimes) * 1000); //延迟几秒，再去请求
            i--;
            _this.processMsg +=
              "<br/>id:" + i + "，开始第：" + retryTimes + "次重试";
          }
        }
      }

      //全部执行完毕，释放按钮
      _this.btnFlag = false;
    },
    selectChange(val) {
      this.initData();
      var colTradeMode = [
        { label: "贸易方式编码", prop: "TrademodeId" },
        { label: "贸易方式名称", prop: "Trademodename" },
      ];
      var tableTradeMode = [{ TrademodeId: "", Trademodename: "" }];

      var colCommodity = [
        { label: "商品编码", prop: "CommodityId" },
        { label: "商品名称", prop: "Commodityname" },
        { label: "年份", prop: "Year" },
        { label: "第一计量单位编码", prop: "Firstuomcode" },
        { label: "第一计量单位名称", prop: "Firstuomname" },
        { label: "第二计量单位编码", prop: "Seconduomcode" },
        { label: "第二计量单位名称", prop: "Seconduomname" },
        { label: "HS编码", prop: "Hscode" },
        { label: "商品描述", prop: "Commoditydescription" },
        { label: "产品英文名称", prop: "Commodityenglishname" },
        { label: "新增时间", prop: "AddTime" },
      ];
      var tableCommodity = [
        {
          CommodityId: "",
          Commodityname: "",
          Year: "",
          Firstuomcode: "",
          Firstuomname: "",
          Seconduomcode: "",
          Seconduomname: "",
          Hscode: "",
          Commoditydescription: "",
          Commodityenglishname: "",
          AddTime: "",
        },
      ];

      var colTradePartner = [
        { label: "贸易伙伴编码", prop: "TradepartnerId" },
        { label: "贸易伙伴名称", prop: "Tradepartnername" },
      ];
      var tableTradePartner = [{ TradepartnerId: "", Tradepartnername: "" }];

      var colProvince = [
        { label: "省市编码", prop: "ProvinceId" },
        { label: "注册地名称", prop: "Provincename" },
      ];
      var tableProvince = [{ ProvinceId: "", Provincename: "" }];

      var colExportCommodity = [
        { label: "序号", prop: "Id" },
        { label: "商品类别", prop: "Commoditycategory" },
        { label: "商品编码范围", prop: "Commoditycoderange" },
        { label: "计量单位", prop: "Uom" },
      ];
      var tableExportCommodity = [
        { Id: "", Commoditycategory: "", Commoditycoderange: "", Uom: "" },
      ];

      var colImportCommodity = [
        { label: "序号", prop: "Id" },
        { label: "商品类别", prop: "Commoditycategory" },
        { label: "商品编码范围", prop: "Commoditycoderange" },
        { label: "计量单位", prop: "Uom" },
      ];
      var tableImportCommodity = [
        { Id: "", Commoditycategory: "", Commoditycoderange: "", Uom: "" },
      ];

      var colUOMAdjustment = [
        { label: "商品编码", prop: "Id" },
        { label: "商品名称", prop: "Commodityname" },
        { label: "计量单位名称（新）", prop: "Newuom" },
        { label: "计量单位名称（旧）", prop: "Olduom" },
      ];
      var tableUOMAdjustment = [
        { Id: "", Commodityname: "", Newuom: "", Olduom: "" },
      ];

      var colTradeData = [
        { label: "商品编码", prop: "CommodityId" },
        { label: "商品名称", prop: "Commodityname" },
        { label: "贸易伙伴编码", prop: "TradepartnerId" },
        { label: "贸易伙伴名称", prop: "Tradepartnername" },
        { label: "贸易方式编码", prop: "TrademodeId" },
        { label: "贸易方式名称", prop: "Trademodename" },
        { label: "注册地编码", prop: "ProvinceId" },
        { label: "注册地名称", prop: "Provincename" },
        { label: "第一数量", prop: "Firstquantity" },
        { label: "第一计量单位", prop: "Firstuomname" },
        { label: "第一数量", prop: "Secondquantity" },
        { label: "第二计量单位", prop: "Seconduomname" },
        { label: "人民币", prop: "AmountRMB" },
      ];
      var tableTradeData = [
        {
          CommodityId: "",
          Commodityname: "",
          TradepartnerId: "",
          Tradepartnername: "",
          TrademodeId: "",
          Trademodename: "",
          ProvinceId: "",
          Provincename: "",
          Firstquantity: "",
          Firstuomname: "",
          Secondquantity: "",
          Seconduomname: "",
          AmountRMB: "",
        },
      ];

      switch (val) {
        case "TradeMode":
          this.cols = colTradeMode;
          this.tableData = tableTradeMode;
          break;
        case "TradePartner":
          this.cols = colTradePartner;
          this.tableData = tableTradePartner;
          break;
        case "Province":
          this.cols = colProvince;
          this.tableData = tableProvince;
          break;
        case "ExportCommodity":
          this.cols = colExportCommodity;
          this.tableData = tableExportCommodity;
          break;
        case "ImportCommodity":
          this.cols = colImportCommodity;
          this.tableData = tableImportCommodity;
          break;
        case "UOMAdjustment":
          this.cols = colUOMAdjustment;
          this.tableData = tableUOMAdjustment;
          break;
        case "Commodity":
          this.cols = colCommodity;
          this.tableData = tableCommodity;
          break;
        case "TradeData":
          this.cols = colTradeData;
          this.tableData = tableTradeData;
          break;
        default:
          this.$message({
            type: "werrorarning",
            message: "请选择需要导入的表",
          });
          break;
      }
      this.tableName = val;
    },
    handleSizeChange(val) {
      console.log("每页 ${val} 条");
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      console.log("当前页: ${val}");
      this.currentPage = val;
    },
    handleChange(file, fileList) {
      //初始化进度数据
      this.initData();
      if (this.tableName == "") {
        this.$message({
          type: "warning",
          message: "请先选择需要导入的表",
        });
        return;
      }
      console.log("handleChange");
      console.log(file, fileList);
      this.fileTemp = file.raw; // file.raw 及上传的excel
    },
    handleExceed(file, fileList) {
      console.log("handleExceed");
      console.log(file, fileList);
      this.$message({
        type: "warning",
        message: "只能读取一个文件,请删除后再重传",
      });
    },
    handleRemove(file, fileList) {
      console.log("handleRemove");
      this.fileTemp = null;
    },
    initData() {
      this.totalCount = 0;
      this.processCount = 0;
      this.errorCount = 0;
      this.processMsg = 0;
      this.percentage = 0;
      this.checked = false;
      this.fileTemp = null;
      this.totalTime = 0;
    },
    fixdata(data) {
      //文件流转BinaryString
      var o = "",
        l = 0,
        w = 10240;
      for (; l < data.byteLength / w; ++l)
        o += String.fromCharCode.apply(
          null,
          new Uint8Array(data.slice(l * w, l * w + w))
        );
      o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
      return o;
    },
    importExcelData(obj) {
      var start0 = performance.now(); //记录时间
      let _this = this;
      this.file = obj;
      let rABS = false; //是否将文件读取为二进制字符串
      let f = this.file;
      let reader = new FileReader();
      let wb; //读取完成的数据
      let arr = [];
      let isCSV = f.name.split(".").reverse()[0] == "csv"; //判断是否是 CSV
      if (isCSV) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
      reader.onload = function (e) {
        var data = e.target.result;
        /*  const view = new DataView(data);
        for (var i = 0; i < view.byteLength; i++) {
          if (view.getInt8(i) == 9) {
            view.setInt8(i, 0);
          }
        } */

        // console.log(view);
        // data = view;
        debugger;
        if (isCSV) {
          data = new Uint8Array(data);
          var temp = new Uint8Array(data.byteLength);
          var start = performance.now(); //记录时间
          var index = 0;
          var byte = 0;
          for (var i = 0; i < data.byteLength; i++) {
            byte = data[i];
            if (byte != 9) {
              temp[index++] = byte;
            }
          }
          data = temp.slice(0, index);

          var end = performance.now(); //记录时间
          var xxx = end - start;
          console.log(`去除\t:${xxx}`);
          var start1 = performance.now(); //记录时间
          let f1 = isUTF8(data);
          if (f1) {
            data = e.target.result;
          } else {
            var str = cptable.utils.decode(936, data);
            wb = XLSX.read(str, { type: "string" });
          }
        } else {
          wb = XLSX.read(data, { type: "binary" });
        }
        const firstSheetName = wb.SheetNames[0];
        const worksheet = wb.Sheets[firstSheetName];
        var headerName = [];
        _this.cols.map((m) => {
          headerName.push(m.prop);
        });
        const Sheet2JSONOpts = {
          header: headerName,
          range: 1,
          raw: false,
        };
        arr = XLSX.utils.sheet_to_json(worksheet, Sheet2JSONOpts);
        var end1 = performance.now(); //记录时间
        var time1 = end1 - start1;
        console.log("解析csv:" + time1);
        var end0 = performance.now(); //记录时间
        var time0 = end0 - start0;
        console.log("总时长:" + time0);
        debugger;
        _this.tableData = arr;
        _this.totalCount = arr.length;
      };
      reader.onloadstart = function (e) {
        _this.msg = "加载开始...";
        console.log("onloadstart");
        console.log(e);
      };
      reader.onloadend = function (e) {
        _this.msg = "加载结束";
        console.log("onloadend");
        console.log(e);
      };
      reader.onerror = function (e) {
        _this.msg = "文件加载发生错误";
        console.log("onerror");
        console.log(e);
      };
      _this.ShowDiv = true;
    },
  },
};
</script>

<style scoped>
.app-container {
  padding-top: 20px;
  height: calc(100vh - 65px);
}

.form-scrollbar {
  height: calc(100vh - 75px);
}

.form-company {
  min-width: 720px;
}

.el-dialog-div {
  height: 290px;
}

.el-dialog-div /deep/ .el-alert {
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.box-card /deep/ .el-card__header {
  padding: 10px 20px;
}

.box-card /deep/ .el-card__body {
  padding: 20px 10px;
}
el-input {
  width: 70%;
}
.explore_right_pages {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
}
.el-icon-arrow-right:before {
  content: "下一页";
}
.el-pagination button:hover {
  color: #999999;
}
.el-pagination button {
  color: #999999;
}
.el-pagination .btn-next {
  width: 60px;
  height: 35px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #cccccc;
  padding-left: 0;
  padding-right: 0;
}

.el-pager li {
  background-color: unset;
}
.el-pager li:hover {
  color: #999999;
}

.el-pager .number {
  width: 35px;
  height: 35px;
  line-height: 35px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #cccccc;
  margin-right: 5px;
  margin-right: 5px;
  color: #999999;
}
.el-pager .number:hover {
  color: #999999;
}
.el-pager li.active {
  border: none;
  cursor: pointer;
  background: #ff9213;
  color: #fff;
}
.el-pager li.active:hover {
  color: #fff;
  background: #ff9213;
}
.el-pager li.btn-quicknext {
  line-height: 28px;
  color: #999;
}
</style>
